package com.qijian.maindata.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qijian.common.annotation.Log;
import com.qijian.common.core.controller.BaseController;
import com.qijian.common.core.domain.AjaxResult;
import com.qijian.common.core.page.TableDataInfo;
import com.qijian.common.enums.BusinessType;
import com.qijian.common.utils.StringUtils;
import com.qijian.common.utils.mybatis.WhereEntityTool;
import com.qijian.common.utils.poi.ExcelUtil;
import com.qijian.common.utils.uuid.IdUtils;
import com.qijian.maindata.domain.Examine;
import com.qijian.maindata.domain.InspectionScheme;
import com.qijian.maindata.domain.Item;
import com.qijian.maindata.domain.PurmPurchaseTakeQtItemRecord;
import com.qijian.maindata.domain.query.ExamineQuery;
import com.qijian.maindata.domain.vo.*;
import com.qijian.maindata.mapper.ItemMapper;
import com.qijian.maindata.service.IExamineService;
import com.qijian.maindata.service.IInspectionSchemeService;
import com.qijian.tool.domain.Storage;
import com.qijian.tool.domain.query.StorageQuery;
import com.qijian.tool.service.IStorageService;
import io.lettuce.core.dynamic.annotation.Param;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 检验项Controller
 *
 * @author qijian
 * @date 2021-11-24
 */
@Api(tags = "质检管理：检验项")
@RestController
@RequiredArgsConstructor
@RequestMapping("/maindata/examine")
public class ExamineController extends BaseController {

    private final IExamineService examineService;
    private final IStorageService storageService;
    private final ItemMapper itemMapper;
    private final IInspectionSchemeService inspectionSchemeService;


    /**
     * 查询检验项列表
     */
    @PreAuthorize("@ss.hasPermi('maindata:examine:list')")
    @GetMapping("/list")
    public TableDataInfo list(ExamineQuery query, IPage<Examine> page) {
        return getDataTable(examineService.pageVo(Page.of(page.getCurrent(), page.getSize()), WhereEntityTool.invoke(query)));
    }

    /**
     * 导出检验项列表
     */
    @PreAuthorize("@ss.hasPermi('maindata:examine:export')")
    @Log(title = "检验项", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void export(ExamineQuery query, HttpServletResponse response) {
        new ExcelUtil<>(Examine.class).exportExcel(response, examineService.list(WhereEntityTool.invoke(query)), "检验项数据");
    }

    /**
     * 获取检验项详细信息
     */
    @PreAuthorize("@ss.hasPermi('maindata:examine:query')")
    @GetMapping(value = "/{examineId}")
    public AjaxResult getInfo(@PathVariable("examineId") Long examineId) {
        return AjaxResult.success(examineService.getById(examineId));
    }

    /**
     * 新增检验项
     */
    @PreAuthorize("@ss.hasPermi('maindata:examine:add')")
    @Log(title = "检验项", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ExamineVo vo) {
        Examine resource = JSONUtil.parse(vo).toBean(Examine.class);
        if (StringUtils.isBlank(resource.getExamineCode())) {
            resource.setExamineCode("JY-" + String.format("%06d", examineService.countWithDel(true)));
        }
        // 文件来源更新
        resource.setExamineId(IdUtils.singletonSnowId());
        if (ObjectUtil.isNotEmpty(vo.getStorage()) && ObjectUtil.isNotEmpty(vo.getStorage().getStorageId())) {
            StorageQuery storageQuery = new StorageQuery();
            storageQuery.setStorageId(vo.getStorage().getStorageId());
            Storage storage = new Storage();
            storage.setClassTable(Examine.class.getSimpleName());
            storage.setClassId(resource.getExamineId());
            storageService.update(storage, WhereEntityTool.invoke(storageQuery));
        }
        return toAjax(examineService.save(resource));
    }

    /**
     * 修改检验项
     */
    @PreAuthorize("@ss.hasPermi('maindata:examine:edit')")
    @Log(title = "检验项", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Examine examine) {
        return toAjax(examineService.updateById(examine));
    }

    /**
     * 删除检验项
     */
    @PreAuthorize("@ss.hasPermi('maindata:examine:remove')")
    @Log(title = "检验项", businessType = BusinessType.DELETE)
    @DeleteMapping("/{examineIds}")
    public AjaxResult remove(@PathVariable List<Long> examineIds) {
        return toAjax(examineService.removeByIds(examineIds));
    }

    /**
     * 根据物料查询对应质检方案
     */
    @Log(title = "根据物料查询对应质检方案")
    //@PreAuthorize("@ss.hasPermi('purchase:purchaseTakeQt:query')")
    @GetMapping(value = "/getQtScheme")
    public AjaxResult getQtScheme(@Param("bomId") Long bomId, @Param("detailId") Long detailId) {
        Item item = itemMapper.selectById(bomId);
        Long schemeId = item.getSchemeId();
        if (Objects.isNull(schemeId)) {
            return AjaxResult.error("未查询到对应质检方案!");
        }
        InspectionScheme scheme = inspectionSchemeService.getById(schemeId);
        if (Objects.isNull(scheme)) {
            return AjaxResult.error("未查询到对应质检方案!");
        }

        PurchaseTakeQtDetailDownNewVo vo = new PurchaseTakeQtDetailDownNewVo();
        vo.setRecords(Arrays.asList(scheme));

        //查询物料默认的质检方案
        InspectionSchemeVo info = inspectionSchemeService.getInfo(schemeId);
        List<InspectionItemVo> detailsVoList = info.getDetailsVoList();
        scheme.setItems(detailsVoList);
        return AjaxResult.success(vo);
    }

}
